package com.ayu.shortlink.settlement.util;

import java.math.BigDecimal;
import java.math.RoundingMode;

// 金钱工具类
public class MoneyUtil {

    /**
     * 默认精度
     */
    private static final int DEFAULT_SCALE = 2;

    /**
     * 默认舍入模式
     */
    private static final RoundingMode DEFAULT_ROUNDING_MODE = RoundingMode.HALF_UP;

    /**
     * 格式化金额
     */
    public static BigDecimal formatMoney(BigDecimal amount) {
        if (amount == null) {
            return BigDecimal.ZERO;
        }
        return amount.setScale(DEFAULT_SCALE, DEFAULT_ROUNDING_MODE);
    }

    /**
     * 金额加法
     */
    public static BigDecimal add(BigDecimal... amounts) {
        BigDecimal sum = BigDecimal.ZERO;
        for (BigDecimal amount : amounts) {
            if (amount != null) {
                sum = sum.add(amount);
            }
        }
        return formatMoney(sum);
    }

    /**
     * 金额减法
     */
    public static BigDecimal subtract(BigDecimal amount1, BigDecimal amount2) {
        if (amount1 == null) {
            amount1 = BigDecimal.ZERO;
        }
        if (amount2 == null) {
            amount2 = BigDecimal.ZERO;
        }
        return formatMoney(amount1.subtract(amount2));
    }

    /**
     * 金额乘法
     */
    public static BigDecimal multiply(BigDecimal amount1, BigDecimal amount2) {
        if (amount1 == null || amount2 == null) {
            return BigDecimal.ZERO;
        }
        return formatMoney(amount1.multiply(amount2));
    }

    /**
     * 金额除法
     */
    public static BigDecimal divide(BigDecimal amount1, BigDecimal amount2) {
        if (amount1 == null || amount2 == null || amount2.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO;
        }
        return amount1.divide(amount2, DEFAULT_SCALE, DEFAULT_ROUNDING_MODE);
    }

    /**
     * 金额比较
     * @return -1：小于，0：等于，1：大于
     */
    public static int compare(BigDecimal amount1, BigDecimal amount2) {
        amount1 = amount1 == null ? BigDecimal.ZERO : amount1;
        amount2 = amount2 == null ? BigDecimal.ZERO : amount2;
        return amount1.compareTo(amount2);
    }

    /**
     * 是否为零
     */
    public static boolean isZero(BigDecimal amount) {
        return amount == null || amount.compareTo(BigDecimal.ZERO) == 0;
    }

    /**
     * 是否大于零
     */
    public static boolean isGreaterThanZero(BigDecimal amount) {
        return amount != null && amount.compareTo(BigDecimal.ZERO) > 0;
    }

    /**
     * 是否小于零
     */
    public static boolean isLessThanZero(BigDecimal amount) {
        return amount != null && amount.compareTo(BigDecimal.ZERO) < 0;
    }
}